class LocalStorageTools {

  remove(key) {
    localStorage.removeItem(key);
  }

  clear() {
    localStorage.clear();
  }

  all() {
    let rs = {};
    let len = localStorage.length;
    for (let i = 0; i < len; i++) {
      let key = localStorage.key(i);
      let value = this.get(key);
      rs[key] = value;
    }
    return rs;
  }

  set(key, val) {
    if (val == null || val == undefined) {
      localStorage.removeItem(key);
    }
    let type = typeof(val);//string  number  object undefined
    let rsVal = {
      type,
      val
    };
    rsVal.version = process.env.V_CODE
    localStorage.setItem(key, JSON.stringify(rsVal));
  }


  //第二个参数表示，是否检测版本，如果希望每次打包，都会忽略上次的配置，应该为true
  get(key, checkVersion) {
    let val = localStorage.getItem(key);
    if (val == null || val == undefined) {
      return val;
    }

    try {
      let obj = JSON.parse(val);
      val = obj.val
      //有版本号，且版本号不一致，则为null
      if (checkVersion && val.version !== process.env.V_CODE) {
        val = null
      }
    } catch (e) {

    }
    return val
  }

}

window.localStorageTools = new LocalStorageTools();
export default new LocalStorageTools();
